package com.aimls.common;

import java.util.Random;

public class TestSubString {

	/**
	 * 字符串按字节截取
	 * 
	 * @param str
	 *            原字符
	 * @param len
	 *            截取长度
	 * @return String
	 * @author ivan
	 * @since 2010.07.05
	 */
	public static String splitString(String str, int len) {
		return splitString(str, len, "...");
	}

	/**
	 * 字符串按字节截取
	 * 
	 * @param str
	 *            原字符
	 * @param len
	 *            截取长度
	 * @param elide
	 *            省略符
	 * @return String
	 * @author ivan
	 * @since 2010.07.05
	 */
	public static String splitString(String str, int len, String elide) {
		
		if (str == null) {
			return "";
		}
		
		byte[] strByte = str.getBytes();
		int strLen = strByte.length;
		int elideLen = 0;
		
		if (len >= strLen || len < 1) {
			return str;
		}
		
		if (len - elideLen > 0) {
			len = len - elideLen;
		}
		
		int count = 0;
		
		for (int i = 0; i < len; i++) {
			
			int value = (int) strByte[i];
			
			if (value < 0) {
				count++;
			}
		}
		
		if (count % 2 != 0) {
			len = (len == 1) ? len + 1 : len - 1;
		}
		
		return new String(strByte, 0, len) + elide.trim();
	}

	public static void main(String[] args) {
		String str = "abcde张三";
		String s = splitString(str, 7);

		System.out.println(s);
		System.out.println(new Random().nextInt(10000));
	}
}